package bcxd.firstline.login;

import java.sql.Connection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.system.ISystem;
import jt.classic.system.context.ISystemContext;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.log.LogManager;
import jt.classic.system.module.ModuleManager;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.mine.StringTool;

import bcxd.firstline.user.AppUser;
import bcxd.firstline.user.manager.AppUserManager;

import com.alibaba.fastjson.JSON;

/**
 * 平台登录
 * 
 * @author mido
 * 
 */
public class BCXDLoginAction extends Action {
	/**
	 * 
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CommonBean4HSQ cbh = new CommonBean4HSQ(request);

		String logid = StringTool.checkString(cbh.getResource().get("logid"));
		String pwd = StringTool.checkString(cbh.getResource().get("pwd"));
		Connection conn = null;
		try {
			SystemDataSource ds = SystemDataSource.getInstance();
			conn = ds.getConnection();

			AppUserManager manager = new AppUserManager(conn);

			AppUser user = manager.checkAppUser(logid, pwd);

			if (user != null) {
				ISystemContext.createSessionUser(request, user);

				LogManager lm = new LogManager(conn);

				lm.log(user, request.getRemoteAddr(), "", "", "bcxdUserLogin",
						"insert", user.iname() + "[" + user.itype() + "]"
								+ " log-in");

				conn.commit();

				if (user.iflag() == -1) {
					request.setAttribute("result", JSON.toJSONString(JSON
							.parse("{success:false, error : " + user.iflag()
									+ "}")));
				} else if (user.iflag() == -2) {
					request.setAttribute("result", JSON.toJSONString(JSON
							.parse("{success:false, error : " + user.iflag()
									+ "}")));
				} else {
					ISystemContext.createSessionUser(request, user);

					request
							.setAttribute("result", JSON.toJSONString(JSON
									.parse("{success:true, userId : '"
											+ user.id() + "', userType : '"
											+ user.itype() + "'}")));
				}
			} else {
				request.setAttribute("result", JSON.toJSONString(JSON
						.parse("{success:false , error : -999}")));
			}
		} catch (Exception ex) {
			conn.rollback();
			ISystem.catchException(this, ex);
			request.setAttribute("result", JSON.toJSONString(JSON
					.parse("{success:false , error : -1000}")));
		} finally {
			SystemDataSource.closeConnection(conn);
		}

		return mapping.findForward("jsonresult");
	}
}
